/* ---------------------------------------------------------------------------
** Server.cpp
** 	Receive packages on robot via WIFI
**
** Author: Roel Postelmans
** -------------------------------------------------------------------------*/ 

#include "server.h"
#include <functional>   // std::bind
#include <thread>
#define ID 2
#define UDP_PORT 3200

using std::cout;

void Server::set_port (int port) {
    udp_port = port;
}
void Server::set_up() {   
using namespace std::placeholders; 
   sockfd=socket(AF_INET,SOCK_DGRAM,0);
   memset(&servaddr,0,sizeof(servaddr));
   servaddr.sin_family = AF_INET;
   servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
   servaddr.sin_port=htons(udp_port);
   auto test= bind(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr));
#ifdef DEBUG
   std::cout << "Server is ready\n" <<test<<"\n";
#endif
}
void Server::listen() {
#ifdef DEBUG
   std::cout << "Waiting for package\n";
#endif
   len = sizeof(cliaddr);
   n = recvfrom(sockfd,&udp_package,sizeof(Udp_package),0,(struct sockaddr *)&cliaddr,&len);   
   Buffer p;
   p.set_package(udp_package,count++);

#ifdef DEBUG
   p.get_package(); 
#endif
}
void server() {
   Server s;
   s.count=0;
   s.set_port(UDP_PORT);
   s.set_up();
   /*Dummy package in statisch package steken*/
   Package p;
   p.nr=-1;
   
   for(;;)
      s.listen();
}


